<script setup>

/**
 * 自定义模板管理
 */
import { ref, onMounted, nextTick, getCurrentInstance  } from "vue";
import { store } from '@/js/store.js';
import { topage } from "@/js/hashRouter.js";
import { debounce, diy_api } from '@/js/api.js';
import { resetnow } from '@/js/function.js';

import { ElMessage } from 'element-plus'

import mobile from '@/pages/diymobile/index.vue'
import mobileView from './diyview.vue'

// 自定义组件名称，保持与缓存名一致可被缓存
defineOptions({ name: 'diymobile' });

const instance = getCurrentInstance();
console.log("🚀 ~ instance:", instance.type)

const props = defineProps({
    hashName: String,
    pageParams: Object,
    xuanze: Boolean,
});
console.log('接收路由参数：', props.pageParams);
//向父级传递消息
const emits = defineEmits(['tohost'])
function sendEmit() {
    emits('tohost', ...arguments);
}

const rowsData = ref([]);
const listMeta = ref({})
const search = ref({ name: '', category: 0 });

const form = ref({})
const dialog = ref(false)
const dialogTitle = ref('')
const dialogView = ref(false);

function onPage(url) {
    location.hash = '#' + url
}

function getList(_page) {
    diy_api.get({ ...search.value }).then((res) => {
        var result = res.data;
        if (result.state) {
            rowsData.value = result.data;
        }
    }).catch((err) => {
        console.log("🚀 ~ diy_api.get ~ err:", err)
    })
}
getList()

onMounted(() => {
})

const method = ref("add");
function rowsAdd() {
    method.value = "add";
    dialogTitle.value = "添加"
    form.value = {};
    dialog.value = true;
}
function rowsEdit(row) {
    method.value = "edit";
    dialogTitle.value = "修改"
    form.value = JSON.parse(JSON.stringify(row));
    dialog.value = true;
}


// 删除
function delData(id) {
    diy_api.del(id).then((res) => {
        var result = res.data;
        if (result.code == 200) {
            getList()
            ElMessage({ message: result.message || "删除成功", type: 'success' })
        } else {
            ElMessage({ message: result.message || "删除失败！", type: 'error' })
        }
    })

}

const multipleSelection = ref([])
function handleSelectionChange(val) {
    multipleSelection.value = val
}
function seleDel() {
    if (multipleSelection.value.length == 0) {
        ElMessage.error({ message: '请选择删除项！' })
        return;
    }
    var id = multipleSelection.value.map(e => e.id)
    delData(id)
}

const viewRef = ref(null)

//修改页面结束事件
function editComplete(obj, type) {
    if(type.viewShow){
		dialogView.value = true;
        nextTick(() => {
            viewRef.value.init?.();
        })
        return;
	}
    dialog.value = false;
    if(type.close){
        return;
    }
    console.log("🚀 ~ 保存结果:", obj)
    getList();
}

function rowsView(row) {
    form.value = JSON.parse(JSON.stringify(row));
    dialogView.value = true;
    nextTick(() => {
        viewRef.value.init?.();
    })
}

//------------------------检索
// 搜索
function souSubmit() {
    getList(1);
}

function newpage() {
    topage('/frame/home/diymobile/pid='+(Date.now()/1000), { pTitle:'编辑模板', msg:'这是传递额外路由参数', id: 101 })
}

</script>

<template>

    <div class="wrapper">
        <el-card style="margin: 5px auto;" v-if="!xuanze">
            <el-popconfirm :title="'确定删除' + multipleSelection.length + '条数据？'" icon-color="red" @confirm="seleDel()">
                <template #reference>
                    <el-button type="danger" plain>批量删除</el-button>
                </template>
            </el-popconfirm>
            <el-button type="warning" plain @click="rowsAdd()">添加</el-button>
            <el-input v-model="search.name" placeholder="请输入检索名称" @keyup.enter.native="souSubmit" clearable
                style="width: 200px;"></el-input>
            <el-button type="primary" plain @click="souSubmit">查询</el-button>
            <hr/>
            <el-button type="primary" plain @click="newpage">新开本页 传递pid</el-button>
        </el-card>

        <el-table ref="multipleTable" class="mytable" :data="rowsData" size="default" style="width: 100%"
            @selection-change="handleSelectionChange" stripe>
            <el-table-column type="selection" width="55" fixed v-if="!xuanze"></el-table-column>
            <el-table-column property="id" label="ID"></el-table-column>
            <el-table-column property="name" label="模板名"></el-table-column>

            <el-table-column label="操作" fixed="right" width="260" v-if="!xuanze">
                <template #default="scope">
                    <el-button size="small" @click="rowsEdit(scope.row)">修改</el-button>
                    <el-button size="small" @click="rowsView(scope.row)">预览</el-button>
                    <el-popconfirm title="确定删除?" icon-color="red" @confirm="delData(scope.row.id)">
                        <template #reference>
                            <el-button size="small"><span style="color: var(--el-color-danger)">删除</span></el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" v-if="xuanze">
                <template #default="scope">
                    <el-button size="small" type="warning"
                        @click="sendEmit(scope.row)">选择</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- <div class="pagination">
        <el-pagination background layout="total, prev, pager, next" :current-page="listMeta.current_page"
            :total="listMeta.total" :page-size="listMeta.per_page" class="right"
            @current-change="getList"></el-pagination>
        <hr>
    </div> -->



        <!-- 修改 & 新增 -->
        <el-drawer v-model="dialog" :title="dialogTitle" direction="btt" size="96%" class="mydrawer" :with-header="false">
            <mobile :form="form" :method="method" @tohost="editComplete" />
        </el-drawer>

        <!-- 预览 -->
        <el-drawer v-model="dialogView" title="预览" direction="btt" size="96%" class="mydrawer" :with-header="false">
            <mobile-view ref="viewRef" :form="form" @tohost="dialogView=false" />
        </el-drawer>
    </div>



</template>

<style scoped>
.wrapper{min-width: 620px;}
:deep(.el-drawer__body){padding: 10px;background-image: radial-gradient(circle, white 40%, #eee, #ddd)}
</style>